package day16.test01;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * @author Xiao
 * @date 2021/8/10
 */
public class ThreadSocket implements Runnable{
    private Socket so;

    public ThreadSocket(Socket so) {
        this.so = so;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            //读入客户端文件，写出至本地
            BufferedInputStream bis = new BufferedInputStream(so.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(
                    "homework/src/day16/test01/"
                            + UUID.randomUUID().toString().replace(
                                    "-","") + ".jpg"));
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
            bos.flush();
            so.shutdownInput();
            System.out.println("服务器上传文件。。。");
            //写出反馈信息至客户端
            BufferedOutputStream bos1 = new BufferedOutputStream(so.getOutputStream());
            bos1.write("文件上传成功...\r\nOver！!!".getBytes());
            bos1.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (so != null) {
                try {
                    so.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
